# coding = utf-8
import os
import cv2
import numpy as np

def Face(frame):
    global names
    model_dir = './Model/'
    faceCascade = cv2.CascadeClassifier(r'./CV2Data/haarcascade_frontalface_default.xml')

    confidence = 150.00
    name = "unknown"

    # pict = cv2.imread("./GQL.0.22.jpg",cv2.IMREAD_GRAYSCALE)
    np_array = np.frombuffer(frame, np.uint8)

    pict = cv2.imdecode(np_array, cv2.IMREAD_GRAYSCALE)

    if pict is not None:
        print("decode successful")
        
    faces = faceCascade.detectMultiScale(
        pict,
        scaleFactor=1.31,
        minNeighbors=2
    )

    # recognizer = cv2.face.LBPHFaceRecognizer_create()
    # recognizer.read(r'./Model/trainer-2021.yml')
    # idnum, confidence = recognizer.predict(pict)
    # # print(confidence)
    # if confidence < 90:
    #     name = names[idnum]
    #     # print("ID:", idnum, ",name:", name)
    #     # break
    # else:
    #     name = "unknown"
    #     # break
    # for (x, y, w, h) in faces:
    #     recognizer = cv2.face.LBPHFaceRecognizer_create()
    #     recognizer.read(r'./Model/trainer-2021.yml')
    #     idnum, confidence = recognizer.predict(pict[y:y + h, x:x + w])
    #     # print(confidence)
    #     if confidence < 90:
    #         name = names[idnum]
    #         # print("ID:", idnum, ",name:", name)
    #         break
    #     else:
    #         name = "unknown"
    #         break
    i=0
    j=0
    for (x, y, w, h) in faces:
        # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        print(i)
        i+=1
        for model_file in os.listdir(model_dir):
            print(j)
            j+=1
            print(model_file)
            if not model_file.endswith('.yml'):  
                continue
            recognizer = cv2.face.LBPHFaceRecognizer_create()
            recognizer.read(r'./Model/' + model_file)
            idnum, confidence = recognizer.predict(pict[y:y + h, x:x + w])
            print(confidence)
            if confidence < 120:
                name = names[idnum]
                # print("ID:", idnum, ",name:", name)
                break
            else:
                name = "unknown"
                break

    return confidence,name


if __name__ == '__main__':
    names = ['GQL', 'jk', 'xy']
    confidence , name = Face()
    print("confidence : {} , name : {}".format(confidence,name))


